﻿using System.Collections.Generic;
using System.Linq;
using ML.Entity;
using ML.IBusiness;
using ML.IRepository;

namespace ML.Business
{
    /// <summary>
    /// 产品分类业务实现类
    /// </summary>
    public class ProductCategoryBusiness : IProductCategoryBusiness
    {
        private readonly IProductCategoryRepository productCategoryRepository;
        private readonly IProductRepository productRepository;
        public ProductCategoryBusiness(IProductCategoryRepository _productCategoryRepository, IProductRepository _productRepository)
        {
            productCategoryRepository = _productCategoryRepository;
            productRepository = _productRepository;
        }

        public BaseResult<Pager<ProductCategoryResponse>> List(ProductCategorySearch productCategorySearch)
        {
            Pager<ProductCategoryResponse> data = productCategoryRepository.List(productCategorySearch);
            return new BaseResult<Pager<ProductCategoryResponse>>(200, data);
        }

        public BaseResult<IEnumerable<DropDownList>> GetListByMerchantId(string id)
        {
            var data = productCategoryRepository.GetListByMerchantId(id);

            //处理成固定的格式返回
            var result = data.Select(n => new DropDownList()
            {
                value = n.Id,
                name = n.Name
            });
            return new BaseResult<IEnumerable<DropDownList>>(200, result);
        }

        public BaseResult<bool> Add(ProductCategoryEntity entity)
        {
            bool isTrue = productCategoryRepository.AddProductCategory(entity);
            if (isTrue)
            {
                return new BaseResult<bool>(200, true);
            }
            return new BaseResult<bool>(201);
        }

        public BaseResult<bool> Update(ProductCategoryEntity entity)
        {
            var isTrue = productCategoryRepository.UpdateProductCategory(entity);
            if (isTrue)
            {
                return new BaseResult<bool>(200, true);
            }
            return new BaseResult<bool>(201, false);
        }

        public BaseResult<bool> Delete(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                return new BaseResult<bool>(1001, false);
            }

            //判断产品分类是否关联产品，如果关联产品则不允许删除
            var data = productRepository.GetListByCategoryId(id);
            if (data.Count() > 0)
            {
                return new BaseResult<bool>(1052, false);
            }

            var isTrue = productCategoryRepository.Delete(id);
            if (isTrue)
            {
                return new BaseResult<bool>(200, true);
            }
            return new BaseResult<bool>(201, false);
        }
    }
}